package cn.glutnn.auth.domain.service.impl;

import cn.glutnn.auth.common.enums.IsDeletedFlagEnum;
import cn.glutnn.auth.domain.convert.AuthPermissionConverter;
import cn.glutnn.auth.domain.entity.AuthPermissionBO;
import cn.glutnn.auth.domain.redis.RedisUtil;
import cn.glutnn.auth.domain.service.AuthPermissionDomainService;
import cn.glutnn.auth.infra.basic.entity.AuthPermission;
import cn.glutnn.auth.infra.basic.service.AuthPermissionService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author:   msh
 * Date:     2025/1/14 下午1:59
 * Description:
 */

@Service
@Slf4j
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {
    @Resource
    private AuthPermissionService authPermissionService;
    @Autowired
    private RedisUtil redisUtil;
    private String authPermissionPrefix = "auth:permission:";

    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        return authPermissionService.save(authPermission);
    }

    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        return authPermissionService.updateById(authPermission);
    }

    @Override
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionConverter.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        return authPermissionService.updateById(authPermission);
    }

    @Override
    public List<String> getPermission(String userName) {
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, userName);
        String permissionValue = redisUtil.get(permissionKey);
        if (!StringUtils.isNotBlank(permissionValue)) {
            return Collections.emptyList();
        }
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue, new TypeToken<List<AuthPermission>>() {
        }.getType());
        return permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
    }
}
